<script lang="ts" setup>
import type { VNodeRef } from 'vue'
import type { DefaultOptionType } from 'ant-design-vue/lib/vc-cascader'
import { ref, reactive, onMounted, onBeforeUpdate } from 'vue'
import { TreeSelect, TreeSelectProps, CascaderProps, SelectProps } from 'ant-design-vue'
import { MinusOutlined, PlusOutlined } from '@ant-design/icons-vue'
import { RoleAddType } from '@/types/modules/role'
import { DeleteOutlined } from '@ant-design/icons-vue'
import useCol from '@/hooks/system/useCol'
import { useI18n } from '@/hooks/web/useI18n'
import { Status } from '@/utils/http/types.d'
import * as api from '@/api/modules/role'

const { t } = useI18n()

const props = defineProps({
  rank: { type: Number },
  isItem: { type: Boolean, default: false },
  isList: { type: Boolean, default: false },
  itemData: {
    type: Object as PropType<RoleAddType>,
    default: () => ({
      name: undefined,
      types: [],
      viewRoutes: [],
    })
  },
  apiTreeData: Object,
  routeTreeData: Object,
})

const { getBindPageCol } = useCol(props.isList)

const formRef = ref()
const refs = ref<any[]>([])
const formState = reactive<Expandable<RoleAddType>>(props.itemData)

const basicRules = {
  name: [
    { max: 32, message: 'Length Error', trigger: 'blur' },
  ],
  types: [
  ],
  viewRoutes: [
  ],
}

onBeforeUpdate(() => {
  refs.value = []
})

const setItemRef = (el: VNodeRef): VNodeRef => {
  if (el) {
    refs.value.push(el)
  }
  return el
}

const filterCascaderOptions = (inputValue: string, path: DefaultOptionType[]) =>
  path.some(
    option =>
      (option.label as string).toLowerCase().indexOf(inputValue.toLowerCase()) >
      -1
  )

const handleBasicOk = async () => {
  let valid = await formRef.value.validate().catch((err: any) => err)
  if (!valid?.errorFields?.length) return valid
  return false
}

const resetBasicForm = () => {
  formRef.value.resetFields()
}

const handleRelateArrOk = async () => {
  let relateArr = []
  let isFailed = false
  for (let i = 0; i < refs.value.length; i++) {
    const result = await refs.value[i].handleOk()
    relateArr.push(result)
    if (!result) {
      isFailed = true
    }
  }
  if (isFailed) return false
  return relateArr
}

const resetRelateArrForm = () => {
  for (let i = 0; i < refs.value.length; i++) {
    ; (refs.value[i] as any).resetForm()
  }
}

const handleOk = async () => {
  const basicResult = await handleBasicOk()
  const relateArrRsult = await handleRelateArrOk()
  if (basicResult && relateArrRsult) {
    return formState
  }
  return false
}

const resetForm = () => {
  resetBasicForm()
  resetRelateArrForm()
}

const emit = defineEmits(['delete'])
const hanldeDeleteData = () => {
  emit('delete', props.rank)
}

defineExpose({ handleOk, resetForm })
</script>
<template>
  <div :class="{ isChild: isItem }">
    <div class="form-wrapper">
      <a-form ref="formRef" :model="formState" :rules="basicRules" :labelWrap="true" @finish="handleOk">
        <a-form-item name="name" label="角色名称" v-bind="getBindPageCol">
          <a-input v-model:value="formState['name']" :placeholder="`角色名称`" allow-clear />
        </a-form-item>
        <a-form-item name="apiPermissions" label="API权限" v-bind="getBindPageCol">
          <TreeSelect v-model:value="formState['apiPermissions']" :tree-data="apiTreeData" tree-checkable allow-clear
            :show-checked-strategy="TreeSelect.SHOW_PARENT" placeholder="API权限" />
        </a-form-item>
        <a-form-item name="routePermissions" label="路由权限" v-bind="getBindPageCol">
          <TreeSelect v-model:value="formState['routePermissions']" :tree-data="routeTreeData" tree-checkable allow-clear
            :show-checked-strategy="TreeSelect.SHOW_PARENT" placeholder="路由权限" />
        </a-form-item>
      </a-form>
    </div>
    <div v-if="isItem" class="del">
      <a-popconfirm :title="t('system.deletePrompt')" placement="top" @confirm="hanldeDeleteData">
        <delete-outlined :style="{ fontSize: '16px', color: '#f00' }" />
      </a-popconfirm>
    </div>
  </div>
</template>

<style lang="less" scoped>
.isChild {
  border: 1px solid @border-color-base;
  padding-top: 18px;
  border-radius: 4px;
  margin-bottom: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;

  &:hover {
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  }

  .del {
    margin: 0 15px;
    cursor: pointer;
  }

  .form-wrapper {
    flex-grow: 2;
  }
}

.ant-picker,
.ant-input-number {
  width: 100%;
}

.empty-data {
  text-align: center;
  color: #d6d6d6;
}
</style>
